import router from './router'
import asyncRoutes from './router/asyncRoutes'
import store from './store'
const whiteList = ['/login', '/404']
// 获取一级权限的标识
const getFirstRoutePermission = (permission) => {
  const firstPermArr = permission.map(item => {
    return item.split(':')[0]
  })
  // 去重
  return [...new Set(firstPermArr)]
}
// 获取二级权限的标识
const getSecondRoutePermission = (permission) => {
  const secondPermArr = permission.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(secondPermArr)]
}
// 根据一级二级权限标识 筛选出对应可展示的动态路由
const getRoutes = (firstPermission, secondPermission, asyncRoutes) => {
  // 判断当前登录人是不是管理员
  if (firstPermission.includes('*')) return asyncRoutes
  const firstRoutes = asyncRoutes.filter(item => firstPermission.includes(item.permission))
  const routes = firstRoutes.map(item => {
    return {
      ...item,
      children: item.children.filter(child => secondPermission.includes(child.permission))
    }
  })
  return routes
}

router.beforeEach((to, from, next) => {
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      // 1.拿到用户的权限信息
      store.dispatch('menu/getPermission').then(res => {
        // 2.根据权限表示 筛选出对应的一级路由的标识
        const firstPermission = getFirstRoutePermission(res)
        // 3.根据权限表示 筛选出对应的二级路由的标识
        const secondPermission = getSecondRoutePermission(res)
        // 4.根据一级权限标识和二级权限标识和动态路由进行筛选
        const routes = getRoutes(firstPermission, secondPermission, asyncRoutes)
        // 5.把筛选的路由，展示在左侧
        // 5.1先把筛选之后的路由添加到路由对象中（跳转）
        routes.forEach(item => router.addRoute(item))
        // 5.2再把筛选之后的路由添加到vuex中（渲染）
        store.commit('menu/setMenuList', routes)
      })
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
